package itpenguin.train.metro;

import itpenguin.train.common.Train;
import itpenguin.train.common.TrainFeed;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;

import com.google.transit.realtime.GtfsRealtime.VehiclePosition.VehicleStopStatus;

public class Metro implements TrainFeed {

	@Override
	public List<Train> getCurrentPositions() throws IOException {
		
        InputStream is = new URL("http://api.metro.net/agencies/lametro/vehicles/").openStream();
        JSONObject envelope = JSONObject.fromObject(IOUtils.toString(is));
		List<Train> list = new ArrayList<Train>();
		
		JSONArray trains = envelope.getJSONArray("items");
		
		for (Object elm : trains) {
			JSONObject jo = (JSONObject) elm;
			Train train = new Train((float) jo.getDouble("latitude"), 
					(float) jo.getDouble("longitude"), VehicleStopStatus.IN_TRANSIT_TO, 
					jo.getString("id"), 
					jo.optString("run_id"), jo.getString("route_id"),
					new Date(System.currentTimeMillis() - jo.getInt("seconds_since_report") * 1000));
			train.setDirection(jo.getString("heading"));
			list.add(train);
		}
		
		return list;
	}

}
